﻿using UnityEngine;
using UnityEngine.Networking;

public class Move : NetworkBehaviour
{
	public GameObject bulletPrefab;

	public override void OnStartLocalPlayer()
	{
		GetComponent<MeshRenderer>().material.color = Color.red;
	}

	[Command]
	void CmdFire()
	{
		// This [Command] code is run on the server!

		// create the bullet object locally
		GameObject bullet = Instantiate(
			bulletPrefab,
			transform.position - transform.forward,
			Quaternion.identity) as GameObject;

		bullet.GetComponent<Rigidbody>().velocity = -transform.forward*4;

		// spawn the bullet on the clients
		NetworkServer.Spawn(bullet);

		// when the bullet is destroyed on the server it will automaticaly be destroyed on clients
		Destroy(bullet, 2.0f);
	}

	void Update()
	{
		if (!isLocalPlayer)
			return;

		float x = Input.GetAxis("Horizontal")*0.1f;
		float z = Input.GetAxis("Vertical")*0.1f;

		transform.Translate(x, 0, z);

		if (Input.GetKeyDown(KeyCode.Space))
		{
			// Command function is called from the client, but invoked on the server
			CmdFire();
		}
	}
}